package com.xyz.frame.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyz.frame.bean.model.FileEntity;
import com.xyz.frame.common.exception.XyzShopBindException;
import com.xyz.frame.dao.FileMapper;
import com.xyz.frame.service.FileService;
import com.xyz.frame.service.QiNiuOssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;


@Service("fileService")
@Slf4j
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {

    @Value("${qiniu.max-size}")
    private Long maxSize;
    @Value("${file.xiangqing}")
    private String xiangqingImg;
    @Value("${file.url}")
    private String xiangqingImgUrl;

    private final QiNiuOssService qiNiuOssService;

    public FileServiceImpl(QiNiuOssService qiNiuOssService) {
        this.qiNiuOssService = qiNiuOssService;
    }

    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new XyzShopBindException("上传文件不能为空");
        }

        if(!this.checkSize(maxSize, file.getSize())){
            throw new XyzShopBindException("上传文件超出规定大小");
        }
        String url = null;
        try{
//            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//            url = qiNiuOssService.upload(file.getBytes(), suffix);
            // 确保目录存在
            Path directory = Paths.get(xiangqingImg);
            log.info("===>upload=>directory:{}",directory);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }

            String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
            log.info("===>upload=>fileName:{}",fileName);
            // 构建完整文件路径
            Path filePath = directory.resolve(fileName);
            Files.copy(file.getInputStream(),filePath);
            url = xiangqingImgUrl+"/xqImgs/"+fileName;
            log.info("===>upload=>url:{}",url);

            FileEntity fileEntity = new FileEntity();
            fileEntity.setUrl(url);
            fileEntity.setCreateTime(new Date());
            log.info("===>upload=>fileEntity:{}",fileEntity);
            this.save(fileEntity);
        }catch (Exception e){
            log.error("文件上传失败", e);
            throw new XyzShopBindException("文件上传失败", e);
        }
        return url;
    }

    public static boolean checkSize(long maxSize, long size) {
        // 单位 M
        int len = 1024 * 1024;
        if(size > (maxSize * len)){
            return false;
        }
        return true;
    }

}